package file

import (
	"bufio"
	"mime/multipart"
	"net/http"
)

// 将文件从上传缓存中移到上传目录中
func Write(s Storage, fh *multipart.FileHeader, path string) string {
	f, err := fh.Open()
	if err != nil {
		return "打开文件失败"
	}
	defer f.Close()
	if err := s.Save(path, f); err != nil {
		return "写入文件失败"
	}
	return ""
}

// 将网络上的文件下载下来并保存在下载目录中
func Download(s Storage, url string, path string) string {
	re, err := http.Get(url)
	if err != nil {
		return "下载网络图片失败"
	} else {
		reader := bufio.NewReaderSize(re.Body, 32 * 1024)
		if err := s.Save(path, reader); err != nil {
			return "写入文件失败"
		}
	}
	return ""
}
